#pragma once
#include"Socket.hpp"
#include<iostream>
#include<pthread.h>
#include<functional>
using func_t=std::function<(std::string&,bool *errno_code)>;
class TcpServer;
class ThreadData
{
    public:
    ThreadData(TcpServer*tcp_this,Net_Work::Socket*sockp)
    :_this(tcp_this)
    ,_sockp(sockp)
    {}
    private:
    TcpServer*_this;
    Net_Work::Socket*_sockp;

};
class TcpServer
{
    public:
    TcpServer(uint16_t port,func_t handler_request)
    :_port(port)
    .
    {

    }
    static void*ThreadRun(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData*td=static_cast<ThreadData*>(args);
        std::string inbufferstream;
        while(true)
        {
            bool ok=true;
            if(!td->_sockp->Recv(&inbufferstream,1024))
            {
                break;
            }
            std::string send_string=td->_this->_hander_request(inbufferstream,&ok);
            if(ok)
            {
                if(!send_string.empty()) td->_sockp->Send(send_string);
            }
            else break;
        }
        td->_sockp->CloseSocket();
        delete td->_sockp;
        delete td;
        return nullptr;
    }
    void Loop()
    {
        while(true)
        {
        std::string peerip;
        uint16_t peerport;
        Net_Work::Socket newsock=_listensock->AcceptConnection(&peerip,&peerport);
        if(newsock==nullptr) continue;
        std::cout<<"获取一个新连接,sockfd "<<newsock.GetSockFd()<<"client info"<<peerip<<":"<<peerport<<std::endl;
        pthread_t tid;
        ThreadData*td=new ThreadData(this,newsock);
        pthread_create(&tid,nullptr,ThreadRun,td);
        }
    }
    private:
    int _port;
    Net_Work::Socket*_listensock;
    public:
    func_t _handler_request;

};